package top.sehnsucht;

import com.alibaba.fastjson.JSON;
import com.ramostear.captcha.HappyCaptcha;
import org.apache.log4j.Logger;
import top.sehnsucht.dao.UserDao;
import top.sehnsucht.dao.impl.UserDaoImpl;
import top.sehnsucht.entity.User;
import top.sehnsucht.service.UserService;
import top.sehnsucht.service.impl.UserServiceImpl;
import top.sehnsucht.vo.Result;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description:
 * @Author: Cai
 * @CreateTime: 2021/12/21
 */

public class LoginServlet extends HttpServlet {
    private Logger logger = Logger.getLogger(this.getClass());

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.addHeader("Access-Control-Allow-Origin","*");
        resp.setContentType("text/html;charset=UTF-8");
        //todo 从数据库查询user并查看是否正确
        UserDao userDao = new UserDaoImpl();
        UserService userService = new UserServiceImpl(userDao);
        if (userService.selectUser(new User(req.getParameter("username"),req.getParameter("password")))) {
            logger.info("账号密码正确");
        } else {
            logger.info("账号密码错误");
            resp.getWriter().print(JSON.toJSONString(Result.fail("用户名或密码错误")));
            return;
        }
        //todo 查看验证码是否正确
        if (HappyCaptcha.verification(req,req.getParameter("captcha"),true)) {
            logger.info(JSON.toJSONString(Result.success("登录成功")));
            resp.getWriter().print(JSON.toJSONString(Result.success("登录成功")));
            Integer stuid = userService.selectUserId(new User(req.getParameter("username"), req.getParameter("password")));
            System.out.println(stuid);
            req.getSession().setAttribute("stuId",stuid);
        } else {
            logger.info("验证码错误");
            resp.getWriter().print(JSON.toJSONString(Result.fail("验证码错误")));
        }
        //todo 使用Result返回
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
